package data;

import database.DataBaseConnection;

import java.sql.*;

public class RegisterUserInfo {
    private String username;
    private String password;
    private String nickname;

    public RegisterUserInfo(String username, String password, String nickname) {
        this.username = username;
        this.password = password;
        this.nickname = nickname;
    }

    public int register() {
        Connection connection = DataBaseConnection.getConnection();
        String isExist = "SELECT * FROM userinfo WHERE username = ?";
        if (connection != null) {
            try {
                PreparedStatement preparedStatement1 = connection.prepareStatement(isExist);
                preparedStatement1.setString(1, this.username);
                ResultSet resultSet = preparedStatement1.executeQuery();
                if (resultSet != null && resultSet.next()) {//username已存在
                    return -1;
                }
                String insert = "INSERT INTO userinfo(username,password,operator) " +
                        "VALUES(?,PASSWORD('" + this.password + "'),?)";
                String select = "SELECT last_insert_id() as count";
                String sql = String.format("%s;%s", insert, select);
                PreparedStatement preparedStatement2 = connection.prepareStatement(sql);
                preparedStatement2.setString(1, this.username);
                preparedStatement2.setString(2, this.nickname);
                boolean hasMoreResultSets = preparedStatement2.execute();
                while (hasMoreResultSets || preparedStatement2.getUpdateCount() != -1) {
                    if (hasMoreResultSets) {// select statement
                        ResultSet set = preparedStatement2.getResultSet();
                        if (set.next()) {
                            return set.getInt("count");
                        }
                    } else {// insert statement
                        int updateCount = preparedStatement2.getUpdateCount();
                        if (updateCount == -1)
                            return 0;
                    }
                    hasMoreResultSets = preparedStatement2.getMoreResults();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }
}
